package cn.hnc.checkapi.service;

import cn.hnc.checkapi.bean.Axis;
import cn.hnc.checkapi.bean.Motor;
import cn.hnc.checkapi.bean.MotorCheck;
import cn.hnc.checkapi.bean.NcVer;
import cn.hnc.checkapi.bean.Product;
import cn.hnc.checkapi.bean.Servo;
import cn.hnc.checkapi.bean.User;
import cn.hnc.checkapi.bean.UserAction;
import cn.hnc.checkapi.redis.SequenceUtils;
import cn.hnc.checkapi.repository.AxisRepository;
import cn.hnc.checkapi.repository.MotorCheckRepository;
import cn.hnc.checkapi.repository.MotorRepository;
import cn.hnc.checkapi.repository.NcVerRepository;
import cn.hnc.checkapi.repository.ProductRepository;
import cn.hnc.checkapi.repository.ServoRepository;
import cn.hnc.checkapi.repository.UserActionRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ProductService {
   @Autowired
   private SequenceUtils sequenceUtils;
   @Autowired
   private ProductRepository productRepository;
   @Autowired
   private NcVerRepository ncVerRepository;
   @Autowired
   private ServoRepository servoRepository;
   @Autowired
   private MotorRepository motorRepository;
   @Autowired
   private UserActionRepository userActionRepository;
   @Autowired
   private AxisRepository axisRepository;
   @Autowired
   private MotorCheckRepository motorCheckRepository;
   @Autowired
   private NodeService nodeService;

   @Transactional
   public List findNeedAdd(Long startId, Long endId) {
      List products = this.productRepository.find(startId, endId);
      List list = new ArrayList();
      Iterator var5 = products.iterator();

      while(var5.hasNext()) {
         Product product = (Product)var5.next();

         try {
            Map map = this.nodeService.dealData(product);
            list.add(map.get("main"));
            list.add(map.get("info"));
         } catch (JsonProcessingException var8) {
            JsonProcessingException e = var8;
            e.printStackTrace();
         }
      }

      return list;
   }

   @Transactional
   public List selByMacSN(String macSN) {
      List products = this.productRepository.findByMacSN(macSN);
      List list = new ArrayList();
      Iterator var4 = products.iterator();

      while(var4.hasNext()) {
         Product product = (Product)var4.next();
         Map map = new HashMap();
         map.put("productId", product.getId());
         SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         Date date = new Date(product.getUploadTime() * 1000L);
         map.put("uploadTime", sf.format(date));
         map.put("customerName", product.getCustomerName());
         map.put("contractCode", product.getContractCode());
         map.put("macSN", product.getMacSN());
         list.add(map);
      }

      return list;
   }

   @Transactional
   public Product save(Product product, User user, String ip) {
      List motors = product.getMotors();
      motors.addAll(product.getMElecDataList());
      Date date = new Date();
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
      String batchId = simpleDateFormat.format(date) + this.sequenceUtils.getAutoFlowCode();
      product.setBatchId(batchId);
      product = (Product)this.productRepository.save(product);
      Long id = product.getId();
      NcVer ncVer = product.getNcVer();
      ncVer.setProductId(id);
      this.ncVerRepository.save(ncVer);
      List servos = product.getServos();
      servos.addAll(product.getMServoVerList());
      Iterator var11 = servos.iterator();

      while(var11.hasNext()) {
         Servo servo = (Servo)var11.next();
         servo.setProductId(id);
      }

      Map aixsMap = new HashMap();
      Iterator var17 = motors.iterator();

      while(true) {
         Motor motor;
         Long axisId;
         do {
            if (!var17.hasNext()) {
               this.motorRepository.saveAll(motors);
               this.servoRepository.saveAll(servos);
               UserAction userAction = new UserAction();
               userAction.setUserId(user.getId());
               userAction.setAction("添加");
               userAction.setActionTime(simpleDateFormat.format(date));
               userAction.setProductId(product.getId());
               userAction.setIp(ip);
               this.userActionRepository.save(userAction);
               return product;
            }

            motor = (Motor)var17.next();
            motor.setProductId(id);
            axisId = null;
            if (!aixsMap.containsKey(motor.getAxisName())) {
               Axis axis = new Axis();
               axis.setAxisName(motor.getAxisName());
               axis.setServoId(motor.getServoId());
               axis.setServoModel(motor.getServoModel());
               axis.setServoProductTime(motor.getServoProductTime());
               axis.setProductId(id);
               axis.setElecId(motor.getElecId());
               axis.setElecModel(motor.getElecModel());
               axisId = ((Axis)this.axisRepository.save(axis)).getId();
               aixsMap.put(motor.getAxisName(), axisId);
            }
         } while(motor.getAverage().equals(0.0) && motor.getCur().equals(0.0) && motor.getMax().equals(0.0) && motor.getMin().equals(0.0));

         axisId = (Long)aixsMap.get(motor.getAxisName());
         MotorCheck motorCheck = new MotorCheck();
         motorCheck.setAverage(motor.getAverage());
         motorCheck.setCur(motor.getCur());
         motorCheck.setMax(motor.getMax());
         motorCheck.setAxisId(axisId);
         motorCheck.setMin(motor.getMin());
         motorCheck.setProductId(motor.getProductId());
         motorCheck.setAxisName(motor.getAxisName());
         motorCheck.setElecName(motor.getElecName());
         this.motorCheckRepository.save(motorCheck);
      }
   }

   @Transactional
   public List findAll() {
      List productList = new ArrayList();
      List products = this.productRepository.findAll();
      Iterator var3 = products.iterator();

      while(var3.hasNext()) {
         Product product = (Product)var3.next();
         Long id = product.getId();
         NcVer ncVer = this.ncVerRepository.findFirstByProductId(id);
         List se = this.servoRepository.findByProductId(id);
         List servos = new ArrayList();
         List mServoVerList = new ArrayList();
         Iterator var10 = se.iterator();

         while(var10.hasNext()) {
            Servo servo = (Servo)var10.next();
            if (!"轴S".equals(servo.getAxisName())) {
               servos.add(servo);
            } else {
               mServoVerList.add(servo);
            }
         }

         List mo = this.motorRepository.findByProductId(id);
         List motors = new ArrayList();
         List mElecDataList = new ArrayList();
         Iterator var13 = mo.iterator();

         while(var13.hasNext()) {
            Motor motor = (Motor)var13.next();
            if (!"轴S".equals(motor.getAxisName())) {
               motors.add(motor);
            } else {
               mElecDataList.add(motor);
            }
         }

         product.setNcVer(ncVer);
         product.setServos(servos);
         product.setMotors(motors);
         product.setMServoVerList(mServoVerList);
         product.setMElecDataList(mElecDataList);
         productList.add(product);
      }

      return productList;
   }

   @Transactional
   public Page selProduct(Integer beginTime, Integer endTime, String customerName, String contractCode, String macSN, String ipcCode, String macNO, Integer queryFlag, String servoId, String servoModel, String elecId, String elecModel, Integer pageNumber) {
      Sort sort = new Sort(Direction.DESC, new String[]{"uploadTime"});
      Pageable pageable = PageRequest.of(0, 10, sort);
      if (queryFlag == 1) {
         beginTime = null;
         endTime = null;
         contractCode = null;
         macSN = null;
         ipcCode = null;
         customerName = null;
         macNO = null;
         servoId = null;
         servoModel = null;
         elecId = null;
         elecModel = null;
      }

      Page productPage;
      if (StringUtils.isBlank(servoId) && StringUtils.isBlank(servoModel) && StringUtils.isBlank(elecId) && StringUtils.isBlank(elecModel)) {
         productPage = this.productRepository.selProduct(beginTime, endTime, customerName, contractCode, macSN, ipcCode, macNO, pageable);
         if (productPage.getTotalPages() == 0) {
            pageable = PageRequest.of(0, 10, sort);
         } else if (pageNumber <= productPage.getTotalPages() - 1) {
            pageable = PageRequest.of(pageNumber, 10, sort);
         } else {
            pageable = PageRequest.of(productPage.getTotalPages() - 1, 10, sort);
         }

         productPage = this.productRepository.selProduct(beginTime, endTime, customerName, contractCode, macSN, ipcCode, macNO, pageable);
         return productPage;
      } else {
         productPage = this.productRepository.selProduct(beginTime, endTime, customerName, contractCode, macSN, ipcCode, macNO, servoId, servoModel, elecId, elecModel, pageable);
         if (productPage.getTotalPages() == 0) {
            pageable = PageRequest.of(0, 10, sort);
         } else if (pageNumber <= productPage.getTotalPages() - 1) {
            pageable = PageRequest.of(pageNumber, 10, sort);
         } else {
            pageable = PageRequest.of(productPage.getTotalPages() - 1, 10, sort);
         }

         productPage = this.productRepository.selProduct(beginTime, endTime, customerName, contractCode, macSN, ipcCode, macNO, servoId, servoModel, elecId, elecModel, pageable);
         return productPage;
      }
   }

   @Transactional
   public void update(Product product, User user, String ip) {
      this.productRepository.save(product);
      List servos = product.getServos();
      servos.addAll(product.getMServoVerList());
      List newMotors = product.getMotors();
      newMotors.addAll(product.getMElecDataList());
      List oldMotors = this.motorRepository.findByProductId(product.getId());
      Iterator var7 = servos.iterator();

      while(var7.hasNext()) {
         Servo servo = (Servo)var7.next();
         Iterator newMotorIterator = newMotors.iterator();
         Iterator oldMotorIterator = oldMotors.iterator();
         List motors = new ArrayList();

         while(newMotorIterator.hasNext()) {
            Motor oldMotor = (Motor)oldMotorIterator.next();
            Motor newMotor = (Motor)newMotorIterator.next();
            String axisName = newMotor.getAxisName();
            if (axisName.equals(oldMotor.getAxisName())) {
               oldMotor.setServoId(newMotor.getServoId());
               oldMotor.setServoModel(newMotor.getServoModel());
               oldMotor.setElecId(newMotor.getElecId());
               oldMotor.setServoProductTime(newMotor.getServoProductTime());
               oldMotor.setElecModel(newMotor.getElecModel());
               motors.add(oldMotor);
            }
         }

         this.motorRepository.saveAll(motors);
         Servo ser = this.servoRepository.findByProductIdAndAxisName(product.getId(), servo.getAxisName());
         if (ser != null) {
            ser.setServoId(servo.getServoId());
            this.servoRepository.save(ser);
         }
      }

      Date date = new Date();
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
      UserAction userAction = new UserAction();
      userAction.setUserId(user.getId());
      userAction.setAction("修改");
      userAction.setActionTime(simpleDateFormat.format(date));
      userAction.setProductId(product.getId());
      userAction.setIp(ip);
      this.userActionRepository.save(userAction);
   }

   @Transactional
   public void delete(Product product, User user, String ip) {
      Long productId = product.getId();
      this.ncVerRepository.deleteByProductId(productId);
      this.servoRepository.deleteByProductId(productId);
      this.motorRepository.deleteByProductId(productId);
      this.productRepository.deleteById(productId);
      Date date = new Date();
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
      UserAction userAction = new UserAction();
      userAction.setUserId(user.getId());
      userAction.setAction("删除");
      userAction.setActionTime(simpleDateFormat.format(date));
      userAction.setProductId(product.getId());
      userAction.setIp(ip);
      this.userActionRepository.save(userAction);
   }
}
